<template>
  <div class="search-box">
    <!-- 搜索输入框 -->
    <el-input
      v-model="keyword"
      placeholder="搜索位置、公交站、地铁站"
      @input="handleInput"
      style="width: 300px"
      class="no-border-input"
      @focus="isInputFocused = true"
      @blur="handleFocused"
    >
      <template #prepend>
        <img src="/img/gaode.png" alt="" class="icon-img" />
      </template>
      <template #append>
        <div class="append-buttons">
          <el-button @click="search" class="btn-icon">
            <i class="iconfont icon-sousuo"></i>
          </el-button>
        </div>
      </template>
    </el-input>
    <el-button @click="handleRoute" class="btn-icon">
      <img src="/img/road.png" alt="路线" class="road-icon" />
    </el-button>
    <div class="panel-list" v-if="!showSuggestions && isInputFocused">
      <div class="item meishi-item" @click="quickSearch('美食')">
        <div class="img-c"><img src="/img/search_food.png" /></div>
        <p class="name ellipsis">美食</p>
      </div>
      <div class="item hotel-item" @click="quickSearch('酒店')">
        <div class="img-c"><img src="/img/search_hotel.png" /></div>
        <p class="name ellipsis">酒店</p>
      </div>
      <div class="item scenic-item" @click="quickSearch('景区')">
        <div class="img-c"><img src="/img/search_view.png" /></div>
        <p class="name ellipsis">景区</p>
      </div>
      <div class="item cinema-item" @click="quickSearch('小区')">
        <div class="img-c"><img src="/img/search_house.png" /></div>
        <p class="name ellipsis">小区</p>
      </div>
    </div>
    <div
      class="poi-history-c"
      v-if="!showSuggestions && isInputFocused && locationHistory.length"
      style="border-top: 1px dashed #dbdee2"
    >
      <ul class="poi-history">
        <li
          class="historyitem"
          v-for="(item, index) in locationHistory"
          :key="index"
          @click="quickSearch(item)"
        >
          <span class="clock-icon"><i class="iconfont icon-clock"></i></span>
          <span class="name ellipsis">{{ item }}</span>
          <span class="del-item"
            ><i
              class="iconfont icon-chacha"
              @click.stop="deleteLocationHistory(index)"
            ></i
          ></span>
        </li>
      </ul>
    </div>
    <!-- 自定义建议列表 -->
    <div class="suggestion-box" v-if="showSuggestions && results.length">
      <ul>
        <li v-for="item in results" :key="item.id" @click="handleSelect(item)">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
  <!-- 路线规划框 -->
  <div class="route-box" v-if="showRouteBox">
    <div class="mode-switch">
      <button
        :class="{ active: routeMode === 'driving' }"
        @click=";(routeMode = 'driving'), (tripMode = '开车去')"
      >
        <i
          class="iconfont icon-jiache"
          style="cursor: pointer; font-size: 25px"
        ></i>
      </button>
      <button
        :class="{ active: routeMode === 'transit' }"
        @click=";(routeMode = 'transit'), (tripMode = '坐公交')"
      >
        <i
          class="iconfont icon-gongjiao"
          style="cursor: pointer; font-size: 25px"
        ></i>
      </button>
      <button
        :class="{ active: routeMode === 'walking' }"
        @click=";(routeMode = 'walking'), (tripMode = '走路去')"
      >
        <i
          class="iconfont icon-buxing"
          style="width: 30px; cursor: pointer; font-size: 25px"
        ></i>
      </button>
      <button @click="CancelRoute">
        <i
          class="iconfont icon-chacha"
          style="cursor: pointer; font-size: 25px"
        ></i>
      </button>
    </div>

    <div class="input-pair">
      <input v-model="start" placeholder="请输入起点" />
      <input v-model="end" placeholder="请输入终点" />
    </div>
    <div class="actions">
      <button @click="planRoute">{{ tripMode }}</button>
      <button @click="ClearRoute" v-if="ShowClearRoute">清除路线</button>
    </div>
  </div>
  <div
    class="plan_wrap"
    v-if="showRouteBox && routeHistory.length && !showRoute"
  >
    <h2 class="history-title">路线搜索记录</h2>
    <ul>
      <li
        v-for="(item, index) in routeHistory"
        :key="index"
        @click="fillRoute(item)"
      >
        {{ item }}
        <i class="iconfont icon-chacha" @click="deleteRouteHistory(index)"></i>
      </li>
    </ul>
  </div>
  <div id="route" v-show="showRoute"></div>
</template>

<script setup>
import { useTimeout } from 'element-plus'
import { ref, inject, onMounted } from 'vue'

const mapRef = inject('map')
const keyword = ref('')
const results = ref([])
const showSuggestions = ref(false)
const showRouteBox = ref(false)
const ShowClearRoute = ref(false)
const routeMode = ref('driving')
const tripMode = ref('开车去')
const start = ref('')
const end = ref('')
const showRoute = ref(false)

const locationHistory = ref(
  JSON.parse(localStorage.getItem('locationHistory') || '[]')
)
const routeHistory = ref(
  JSON.parse(localStorage.getItem('routeHistory') || '[]')
)

let driving, walking, transit // 路径服务实例

let placeSearch = null
let autoComplete = null
const isInputFocused = ref(false)

onMounted(() => {})
// 搜索关键词（用于按钮点击）
const search = () => {
  if (!placeSearch) {
    const map = mapRef.value
    placeSearch = new AMap.PlaceSearch({ map })
  }
  console.log(keyword.value)
  if (!keyword.value) return
  placeSearch.search(keyword.value, (status, result) => {
    if (status === 'complete' && result.poiList) {
      results.value = result.poiList.pois
      showSuggestions.value = true
      saveLocationHistory(keyword.value)
    }
  })
}
function quickSearch(word) {
  const map = mapRef.value
  if (!placeSearch) {
    placeSearch = new AMap.PlaceSearch({
      map,
      pageSize: 10,
    })
  }

  AMap.plugin('AMap.Geolocation', () => {
    const geolocation = new AMap.Geolocation()
    geolocation.getCurrentPosition((status, result) => {
      if (status === 'complete') {
        const pos = result.position
        placeSearch.searchNearBy(word, pos, 10000, (status, result) => {
          if (status === 'complete' && result.poiList) {
            results.value = result.poiList.pois
            showSuggestions.value = true
            keyword.value = word
            saveLocationHistory(keyword.value)
          } else {
            results.value = []
            showSuggestions.value = false
          }
        })
      }
    })
  })
}
// 自动建议搜索
const querySearch = (queryString, cb) => {
  autoComplete = new AMap.AutoComplete({ city: '全国' })
  if (!autoComplete || !queryString) return cb([])

  autoComplete.search(queryString, (status, result) => {
    if (status === 'complete' && result.tips) {
      const suggestions = result.tips.filter((tip) => tip.location)
      results.value = suggestions
      showSuggestions.value = true
      cb(suggestions)
    } else {
      results.value = []
      showSuggestions.value = false
      cb([])
    }
  })
}

// 输入时触发显示
import { nextTick } from 'vue'

const handleInput = (val) => {
  if (!val) {
    results.value = []
    showSuggestions.value = false
    return
  }

  querySearch(val, (suggestions) => {
    nextTick(() => {
      results.value = suggestions
      showSuggestions.value = suggestions.length > 0
    })
  })
}

function handleFocused() {
  setTimeout(() => {
    isInputFocused.value = false
  }, 500)
}
// 选中某项
const handleSelect = (poi) => {
  const map = mapRef.value
  if (poi && poi.location && map) {
    const [lng, lat] = [poi.location.lng, poi.location.lat]
    map.setZoomAndCenter(16, [lng, lat])
  }
  keyword.value = poi.name
  saveLocationHistory(keyword.value)
  showSuggestions.value = false
}

function handleRoute() {
  isInputFocused.value = false
  showRouteBox.value = true
  const map = mapRef.value
  driving = new AMap.Driving({ map: map, panel: route })
  walking = new AMap.Walking({ map: map, panel: route })
  transit = new AMap.Transfer({ map, city: '杭州', panel: route }) // 城市按需修改
}

function planRoute() {
  showRoute.value = true
  if (!start.value || !end.value) {
    alert('请填写起点和终点')
    return
  }
  const search = new AMap.PlaceSearch({
    city: '全国',
  })

  // 查起点
  search.search(start.value, (status1, result1) => {
    if (status1 !== 'complete' || !result1.poiList?.pois.length) {
      alert('未找到起点')
      return
    }
    const startLoc = result1.poiList.pois[0].location

    // 查终点
    search.search(end.value, (status2, result2) => {
      if (status2 !== 'complete' || !result2.poiList?.pois.length) {
        alert('未找到终点')
        return
      }
      const endLoc = result2.poiList.pois[0].location

      // 路径规划
      if (routeMode.value === 'driving') {
        driving.search(startLoc, endLoc)
      } else if (routeMode.value === 'walking') {
        walking.search(startLoc, endLoc)
      } else if (routeMode.value === 'transit') {
        transit.search(startLoc, endLoc)
      }
      ShowClearRoute.value = true
      saveRouteHistory(start.value, end.value)
    })
  })
}

function CancelRoute() {
  showRouteBox.value = false
  driving.clear()
  walking.clear()
  transit.clear() // 城市按需修改
  showRoute.value = false
  ShowClearRoute.value = false
}
function ClearRoute() {
  driving.clear()
  walking.clear()
  transit.clear() // 城市按需修改
  showRoute.value = false
  ShowClearRoute.value = false
}

function saveLocationHistory(keyword) {
  if (!keyword) return
  locationHistory.value = [
    keyword,
    ...locationHistory.value.filter((k) => k !== keyword),
  ].slice(0, 10) // 最多存10条
  localStorage.setItem('locationHistory', JSON.stringify(locationHistory.value))
}

function saveRouteHistory(startPoint, endPoint) {
  const route = `${startPoint} → ${endPoint}`
  routeHistory.value = [
    route,
    ...routeHistory.value.filter((r) => r !== route),
  ].slice(0, 10)
  localStorage.setItem('routeHistory', JSON.stringify(routeHistory.value))
}

function fillRoute(routeStr) {
  const [s, e] = routeStr.split(' → ')
  start.value = s
  end.value = e
}

// 删除位置历史单条
function deleteLocationHistory(index) {
  locationHistory.value.splice(index, 1)
}

// 删除路线历史单条
function deleteRouteHistory(index) {
  routeHistory.value.splice(index, 1)
}
</script>

<style scoped>
@import 'http://at.alicdn.com/t/c/font_4989319_7okbm5cgvw6.css';
.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 999;
  background: white;
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0 0 10px #ccc;
}

.icon-img {
  width: 34px;
  height: 34px;
}

.btn-icon {
  padding: 6px 8px;
  border: none;
}
.road-icon {
  width: 16.5px;
  height: 18px;
}
.panel-list {
  box-sizing: border-box;
  height: 100%;
  padding: 0 14px;
  padding-top: 2px;
}
.panel-list .item {
  width: 25%;
  height: 100%;
  float: left;
  text-align: center;
  cursor: pointer;
}
.img-c {
  width: 46px;
  height: 46px;
  overflow: hidden;
  margin: 0 auto;
  margin-top: 15px;
}
.img-c img {
  width: 100%;
  height: 100%;
  margin: 0;
}
.poi-history-c {
  top: 140px;
  left: 10px;
  width: 342px;
  position: fixed;
  background: #fff;
}
.poi-history-c .poi-history {
  position: relative;
  max-height: 192px;
  margin: 4px 0;
}
.poi-history-c .poi-history .historyitem {
  list-style: none;
  font-size: 13px;
  cursor: pointer;
  color: #9b9faf;
  height: 32px;
  line-height: 32px;
  padding-left: 1px;
  display: flex;
}
.poi-history-c .poi-history .historyitem .clock-icon {
  display: inline-block;
  margin-right: 8px;
}
.poi-history-c .poi-history .historyitem .ellipsis {
  text-overflow: ellipsis;
  white-space: nowrap;
}
.poi-history-c .poi-history .historyitem .del-item {
  display: inline-block;
  line-height: 32px;
  vertical-align: top;
  transform: scale(0.6);
  margin-left: 4px;
}

.suggestion-box {
  width: 320px;
  font-size: 13px;
  background: #fff;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 4px 4px;
  position: absolute;
  top: 46px; /* 高度要和输入框对齐 */
  left: 0;
  z-index: 1000;
}

.suggestion-box ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.suggestion-box li {
  padding: 8px 12px;
  cursor: pointer;
}

.suggestion-box li:hover {
  background-color: #f0f0f0;
}

.route-box {
  background: #3d93fd;
  border: 1px solid #ccc;
  padding: 12px;
  width: 360px;
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  border-radius: 4px;
  box-shadow: 0 0 10px #ccc;
}

.mode-switch {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}
.mode-switch button {
  flex: 1;
  padding: 6px;
  border: none;
  background: #3d93fd;
  color: #e0e0e0;
}
.mode-switch .active {
  color: white;
}
.input-pair {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 10px;
}
.input-pair input {
  height: 34px;
  padding: 6px;
  border: none;
  background: #3587eb;
  color: #e1f1ff;
}
.input-pair input::placeholder {
  color: #acd7ff;
}
.actions {
  display: flex;
  justify-content: space-between;
  direction: rtl;
}
.actions button {
  height: 32px;
  background: #559ffb;
  border: none;
  padding: 0 25px;
  font-size: 14px;
  color: #fff;
}
#route {
  width: 360px;
  font-size: 13px;
  background: #fff;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 4px 4px;
  position: absolute;
  top: 195px;
  left: 10px;
  z-index: 999;
}
.plan_wrap {
  width: 360px;
  padding-bottom: 20px;
  color: #333;
  background: #fff;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 4px 4px;
  position: absolute;
  top: 195px;
  left: 10px;
  z-index: 999;
}
.plan_wrap h2 {
  height: 46px;
  line-height: 46px;
  font-size: 14px;
  border-bottom: 1px solid #e8e8e8;
  color: #414141;
  margin: 0 14px;
  font-weight: 400;
}
.plan_wrap ul li {
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  padding: 0 14px;
  color: #666867;
  overflow: hidden;
  cursor: pointer;
  background-size: 14px;
}
</style>
<style>
.el-input-group__prepend {
  width: 20px;
  box-shadow: none !important;
}
.el-input__wrapper {
  box-shadow: none !important;
}
.el-input-group__append {
  background: #fff !important;
  box-shadow: none !important;
}
.el-select__wrapper {
  box-shadow: none !important;
}
</style>
